let tbody = document.querySelector('tbody');
let table = document.querySelector('table');
let btn = document.querySelector('button');
let count = document.querySelector('.count');
let time = document.querySelector('.time');
let blocks = document.getElementsByClassName('block');
let getArr = [];
let flag = true;
let maxCount = 15;
let timeVal = 0;
let isFirstOpen = true;
let col = parseInt(Math.sqrt(maxCount * 5));
let row = col;
let winNum = 0;

getTbody();
count.innerText = `${maxCount}`;
btn.style.cursor = `default`;

btn.addEventListener('click', () => {
  if (!flag) {
    flag = true;
    btn.style.cursor = `default`;
    timer = setInterval(() => {
      time.innerText = `${++timeVal}`;
    }, 1000);
    count = document.querySelector('.count');
    time.innerText = `0`;
    tbody.innerHTML = ``;
    btn.innerText = `游戏中`;
    winNum = 0;
    timeVal = 0;
    count.innerText = `${maxCount}`;
    console.log(count.innerText);
    isFirstOpen = true;
    getTbody();
  }
});

/**
 * 生成矩阵,返回对应的二维数组
 */
function getTbody() {
  getArr = [];
  tbody = document.querySelector('tbody');
  for (let i = 0; i < row; i++) {
    let newTr = document.createElement('tr');
    for (let j = 0; j < col; j++) {
      let newTd = document.createElement('td');
      newTd.classList.add('block');
      newTd.addEventListener('mousedown', (e) => {
        clickBlock(i, j, e);
      });
      newTr.appendChild(newTd);
    }
    tbody.appendChild(newTr);
  }

  //一维数组 -> 二维数组
  [...blocks].forEach((item, index) => {
    index % col === 0 && getArr.push([]);
    getArr[parseInt(index / col)].push(blocks[index]);

    // 初始化自定义的计雷数
    item.count = 0;
  });

  return getArr;
}

/**
 * 左右键点击事件
 */
function clickBlock(i, j, e) {
  if (getArr[i][j].isOpen || !flag) {
    return;
  }

  if (e.button == 0) {
    //第一次点击，增加雷
    if (isFirstOpen) {
      isFirstOpen = false;
      count = 0;
      getArr[i][j].isBomb = false;

      while (count < maxCount) {
        let a = Math.floor(Math.random() * row);
        let b = Math.floor(Math.random() * col);
        console.log(a, b);

        if (!(a == i && b == j) && !getArr[a][b].isBomb) {
          getArr[a][b].isBomb = true;
          count++;

          for (let x = a - 1; x <= a + 1; x++) {
            for (let y = b - 1; y <= b + 1; y++) {
              if (x > -1 && y > -1 && x < row && y < col) {
                getArr[x][y].count++;
              }
            }
          }
        }
      }
    }
    openBlock(i, j);
    win(i, j);
    //打开方格
    function openBlock(i, j) {
      getArr[i][j].isOpen = true;
      getArr[i][j].style.backgroundColor = `#ccc`;
      getArr[i][j].style.cursor = `default`;

      if (getArr[i][j].isBomb) {
        getArr[i][j].innerHTML = `<i class="iconfont icon-zhadan"></i>`;

        for (let x = 0; x < row; x++) {
          for (let y = 0; y < col; y++) {
            if (!getArr[x][y].isOpen && getArr[x][y].isBomb) {
              getArr[x][y].isOpen = true;
              getArr[x][y].style.backgroundColor = `#ccc`;
              getArr[x][y].style.cursor = `default`;
              getArr[x][y].innerHTML = `<i class="iconfont icon-zhadan"></i>`;
            }
          }
        }
        btn.innerText = `重新开始`;
        clearInterval(timer);
        btn.style.cursor = `pointer`;
        flag = false;

        alert('游戏结束');
      } else if (!getArr[i][j].count) {
        for (let x = i - 1; x < i + 2; x++) {
          for (let y = j - 1; y < j + 2; y++) {
            if (
              x > -1 &&
              y > -1 &&
              x < row &&
              y < col &&
              !getArr[x][y].isOpen &&
              !getArr[x][y].isBomb
            ) {
              openBlock(x, y);
            }
          }
        }
      } else {
        getArr[i][j].innerText = getArr[i][j].count;
      }
    }
  } else if (e.button == 2) {
    if (!(getArr[i][j].isOpen)) {
      count = document.querySelector('.count');
      if (
        getArr[i][j].innerHTML !==
        `<i class="iconfont icon-tubiaozhizuomoban-"></i>`
      ) {
        getArr[i][
          j
        ].innerHTML = `<i class="iconfont icon-tubiaozhizuomoban-"></i>`;
        count.innerText = `${parseInt(--count.innerText)}`;
      } else {
        getArr[i][j].innerHTML = ``;
        count.innerText = `${parseInt(++count.innerText)}`;
      }
    }
  }
}

/**
 * 阻止右键菜单
 */
table.addEventListener('contextmenu', (e) => {
  e.preventDefault();
});

/**
 * 计时器
 */
let timer = setInterval(() => {
  time.innerText = `${++timeVal}`;
}, 1000);

/**
 * 游戏胜利
 */

function win(i, j) {
  if (!getArr[i][j].isBomb && getArr[i][j].isOpen) {
    winNum++;
  }
  if (winNum == col * row - maxCount) {
    btn.innerText = `开始游戏`;
    clearInterval(timer);
    btn.style.cursor = `pointer`;

    for (let x = 0; x < row; x++) {
      for (let y = 0; y < col; y++) {
        if (!getArr[x][y].isOpen && getArr[x][y].isBomb) {
          getArr[x][y].isOpen = true;
          getArr[x][y].style.backgroundColor = `#ccc`;
          getArr[x][y].style.cursor = `default`;
          getArr[x][y].innerHTML = `<i class="iconfont icon-zhadan"></i>`;
        }
      }
    }

    flag = false;
    alert('游戏胜利');
  }
}
